"""
Django管理命令：加载题目数据到数据库
使用方法：python manage.py load_questions
"""

from django.core.management.base import BaseCommand
from challenge.models import Level, Question, QuestionOption
from challenge.questions_data import LEVELS_DATA, QUESTIONS_DATA


class Command(BaseCommand):
    help = '加载预定义的关卡和题目数据到数据库'

    def handle(self, *args, **options):
        self.stdout.write('开始加载题目数据...')
        
        # 清空现有数据（可选）
        # Level.objects.all().delete()
        # Question.objects.all().delete()
        # QuestionOption.objects.all().delete()
        
        # 加载关卡数据
        for level_data in LEVELS_DATA:
            level, created = Level.objects.get_or_create(
                level_id=level_data['level_id'],
                defaults={'level_name': level_data['level_name']}
            )
            if created:
                self.stdout.write(f'创建关卡: {level.level_name}')
        
        # 加载题目数据
        for question_data in QUESTIONS_DATA:
            try:
                level = Level.objects.get(level_id=question_data['level_id'])
                
                # 创建或更新题目
                question, created = Question.objects.get_or_create(
                    question_id=question_data['question_id'],
                    defaults={
                        'level': level,
                        'content': question_data['content'],
                        'correct_option_index': question_data['correct_option_index']
                    }
                )
                
                if created:
                    self.stdout.write(f'创建题目: {question.content[:30]}...')
                
                # 创建选项
                for i, option_content in enumerate(question_data['options'], 1):
                    option, created = QuestionOption.objects.get_or_create(
                        question=question,
                        content=option_content,
                        defaults={'option_id': question.question_id * 10 + i}
                    )
                    
                    if created:
                        self.stdout.write(f'  创建选项: {option_content[:20]}...')
                        
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'加载题目失败: {question_data["content"]} - {str(e)}'))
        
        self.stdout.write(self.style.SUCCESS('题目数据加载完成！'))
        
        # 统计信息
        level_count = Level.objects.count()
        question_count = Question.objects.count()
        option_count = QuestionOption.objects.count()
        
        self.stdout.write(f'关卡数量: {level_count}')
        self.stdout.write(f'题目数量: {question_count}')
        self.stdout.write(f'选项数量: {option_count}')